package section

import (
	"context"

	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type AttachPostToSectionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAttachPostToSectionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AttachPostToSectionLogic {
	return &AttachPostToSectionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AttachPostToSectionLogic) AttachPostToSection(in *backend.SectionPostInfo) (*backend.BaseResp, error) {
	if in.SectionId == nil || *in.SectionId == 0 {
		return nil, errorx.NewInvalidArgumentError("common.validationError")
	}

	if in.PostId == nil || in.PostType == nil || *in.PostId == 0 || *in.PostType == 0 {
		return nil, errorx.NewInvalidArgumentError("common.validationError")
	}

	filterMap := make(map[string]map[string][]any)
	filterMap[model.SectionPostRelationshipColumns.SectionID] = map[string][]any{
		"equalTo": {*in.SectionId},
	}
	filterMap[model.SectionPostRelationshipColumns.PostID] = map[string][]any{
		"equalTo": {*in.PostId},
	}
	filterMap[model.SectionPostRelationshipColumns.PostType] = map[string][]any{
		"equalTo": {*in.PostType},
	}
	list, _, err := l.svcCtx.Section.GetRelPostList(l.ctx, model.M{
		"pageSize": uint64(1),
	}, -1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var rel *model.SectionPostRelationship
	if len(list) > 0 {
		rel = list[0]
		if in.Sort != nil {
			rel.Sort = uint16(*in.Sort)
		}
	} else {
		var sort uint16
		if in.Sort != nil {
			sort = uint16(*in.Sort)
		} else {
			sort = uint16(globalkey.SystemDefaultSort)
		}

		rel = &model.SectionPostRelationship{
			SectionID: *in.SectionId,
			PostID:    *in.PostId,
			PostType:  uint8(*in.PostType),
			Sort:      sort,
		}
	}

	err = l.svcCtx.Section.AttachPostToSection(l.ctx, nil, rel)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.BaseResp{
		Msg: i18n.CreateSuccess,
	}, nil
}
